<?php
include_once __DIR__.'/config/env_config.php';
include_once __DIR__.'/vendor/autoload.php';
include_once __DIR__.'/lib/WishCrawler.php';

use Wish\WishClient;

$ticketsDataFile = __DIR__."/data/tickets.json";
$tickets = json_decode(file_get_contents($ticketsDataFile), true);

$action = !empty($_REQUEST['a']) ? $_REQUEST['a'] : '';
if ($action == 'reply_ticket') {
    $response = array('status'=>0, 'msg'=>'');
    if (empty($_POST['ticket_id']) || empty($_POST['reply'])) {
        $response['msg'] = '参数不完整';
        echo json_encode($response);
        die;
    }
    $ticketId = $_POST['ticket_id'];
    $reply = $_POST['reply'];

    try {
        $client = new WishClient(WISH_ACCESS_TOKEN, 'prod');
        $client->replyToTicketById($ticketId, $reply);

        $ticket = WishCrawler::crawlTicket($ticketId);
        $tickets[$ticketId] = $ticket;
        file_put_contents($ticketsDataFile, json_encode($tickets));
        $response['status'] = 1;
        $response['msg'] = 'success';
        echo json_encode($response);
    } catch (\Exception $e) {
        $response['msg'] = $e->getMessage();
        echo json_encode($response);
    }
    die;
} elseif ($action == 'view_ticket') {
    $response = array('status'=>0, 'msg'=>'', 'data' => array());
    if (empty($_POST['ticket_id'])) {
        $response['msg'] = '参数不完整';
        echo json_encode($response);
        die;
    }
    $ticketId = $_POST['ticket_id'];

    try {
        $client = new WishClient(WISH_ACCESS_TOKEN, 'prod');
        $ticket = $client->getTicketById($ticketId);
        $response['data'] = $ticket->replies;
        $response['status'] = 1;
        $response['msg'] = 'success';
    } catch (\Exception $e) {
        $response['msg'] = $e->getMessage();
    }
    echo json_encode($response);
    die;
}

$lastUpdate = filemtime($ticketsDataFile);
uasort($tickets, function($a, $b) {
    return $a['open_date'] < $b['open_date'];
});
$wishRepliedTickets = array();
$otherTickets = array();
foreach ($tickets as $ticketId => $ticket) {
    $lastReply = end($ticket['replies']);
    $lastReplyMessage = $lastReply['message'];
    if ($lastReply['sender_id'] == 3) {
        $wishRepliedTickets[$ticketId] = $ticket;
    } else {
        $otherTickets[$ticketId] = $ticket;
    }
}
$tickets = $wishRepliedTickets + $otherTickets;
$page = 'recent_tickets';
include(__DIR__.'/tpl/tickets.html');